<?php
namespace app\know\controller;

use app\know\controller\AdminKnowBaseController;
use app\know\validate\KnowledgePointValidate;
use app\know\validate\TeachingMaterialKnowledgePointValidate;
use app\know\model\KnowledgePointModel;
use app\know\model\TeachingMaterialKnowledgePointModel;
use app\know\model\MaterialModel;
use app\know\model\SysConfigModel;
use think\facade\Db;
use think\facade\Log;

/**
 * Class AdminKnowledgePointController 知识点管理控制器
 * @package app\know\controller
 */
class AdminKnowledgePointController extends AdminKnowBaseController
{
    /**
     * 知识点
     * @adminMenu(
     *     'name'   => '知识点',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 33000,
     *     'icon'   => '',
     *     'remark' => '知识点',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_knowledge_point_index_view');

        if (!empty($content)) 
		{
            return $content;
        }

		$chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $nav = $this->request->param('nav', 'list');

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();
        $stars = SysConfigModel::where(['type' => 'STAR', 'is_delete' => 0])->select();

		$this->assign('stars', $stars);
        $this->assign('materials', $materials);
        $this->assign('material_uuid', $material_uuid);
        $this->assign('chapter_uuid', $chapter_uuid);
        $this->assign('nav', $nav);

        return $this->fetch();
    }
	
    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.is_delete' => 0];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }
        if ($material_uuid)
        {
            $where['a.material_uuid'] = $material_uuid;
        }

        $model = new KnowledgePointModel();
        $count = $model->where($where)
                    ->alias('a')
                    ->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_material c', 'a.material_uuid = c.uuid')
                    ->leftJoin('cmf_know_chapter d', 'a.chapter_uuid = d.uuid and a.material_uuid = d.relate_uuid')
                    ->page($pageNumber, $pageSize)
                    ->field('a.*, c.name as teaching_name, d.name as chapter_name')
                    ->select();
        $stars = SysConfigModel::where(['type' => 'STAR', 'is_delete' => 0])->select();

        foreach ($rows as $k => $v)
        {
            $v['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($v['analysis']));
            foreach ($stars as $st)
            {
                if ($v['star_code'] === $st['key'])
                {
                    $rows[$k]['star'] = $st['value'];
                    break;
                }
            }
        }

        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];
        
        try 
		{
			$model = new KnowledgePointModel();
			$param['uuid'] = $model->getUUID();
            $this->validateFailError($param, 'KnowledgePoint.add');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        Db::startTrans();
        try 
        {
            $row = KnowledgePointModel::create($param);
            if (empty($row)) 
            {
                throw new Exception('生词添加失败');
            }
            // 如果添加生词时包含章节信息，自动添加到章节生词表
            if ($param['material_uuid'] && $param['chapter_uuid'])
            {
                $tm = [
                    'teaching_uuid' => $param['material_uuid'],
                    'chapter_uuid' => $param['chapter_uuid'],
                    'knowledge_point_uuid' => $param['uuid'],
                    'create_user' => $user['user_login'],
                ];
                $this->validateFailError($tm, 'TeachingMaterialKnowledgePoint.add');
                
                $row = TeachingMaterialKnowledgePointModel::create($tm);
                if (empty($row)) 
                {
                    throw new Exception('资料生词添加失败');
                }
            }
            Db::commit();
        } 
        catch (\Exception $e) 
        {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->opLog([
            'table_name' => $model->getTableName(),
            'sql' => KnowledgePointModel::getLastSql(),
            'create_user' => $user['user_login'],
        ]);
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'KnowledgePoint.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
		{
            KnowledgePointModel::where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => (new KnowledgePointModel())->getTableName(),
                'sql' => KnowledgePointModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'KnowledgePoint.edit');
        } 
		catch (ValidateException $e) 
		{
            $this->result('', 0, $e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        Db::startTrans();
        try 
		{
            $teaching_uuid = $param['material_uuid'];
            $chapter_uuid = $param['chapter_uuid'];

            KnowledgePointModel::where('id', $id)->save($param);

            if ($teaching_uuid && $chapter_uuid)
            {
                $d = KnowledgePointModel::where('id', $id)->find();
                $w = [
                    'teaching_uuid' => $teaching_uuid,
                    'chapter_uuid' => $chapter_uuid,
                    'knowledge_point_uuid' => $d['uuid'],
                ];

                $row = TeachingMaterialKnowledgePointModel::where($w)->find();
                if (empty($row)) 
                {
                    $w['create_user'] = $user['user_login'];
                    $this->validateFailError($w, 'TeachingMaterialKnowledgePoint.add');
    
                    $row = TeachingMaterialKnowledgePointModel::create($w);
                    if (empty($row)) 
                    {
                        throw new Exception('资料知识点添加失败');
                    }
                }
            }

            $this->opLog([
                'table_name' => (new KnowledgePointModel())->getTableName(),
                'sql' => KnowledgePointModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
            Db::commit();
        } 
		catch (\Throwable $th) 
		{
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('修改成功');
    }

    public function maxOrder()
    {
        $order = KnowledgePointModel::max('order_number');
        $this->success('', '', $order);
    }

    public function search()
    {
        $txt = $this->request->param('txt', '');

        $model = new KnowledgePointModel();
        $rows = $model->where('a.content','like', $txt . '%')
                    ->alias('a')
                    ->page(1, 10)
                    ->select();
                
        $this->success('', null, $rows);
    }

    public function getItem()
    {
        $id = $this->request->param('id', '');

        $where = ['a.is_delete' => 0, 'a.id' => $id];
        $model = new KnowledgePointModel();
        $rows = $model->where($where)
                    ->alias('a')
                    ->find();
        $rows['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($rows['analysis']));

        $this->success('', null, $rows);
    }
}
